
import React, {useState} from 'react';
import { Form, Input, Button, DatePicker, Select } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { cloneDeep } from 'lodash'

// ! perfect form 内层增减表单项

const { Option } = Select
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};
const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};
const areas = [
  { label: "Beijing", value: "Beijing" },
  { label: "Shanghai", value: "Shanghai" }
];

const type = [
  { text: "免费", value: "free" },
  { text: "付费", value: "unfree" }
];

const sights = {
  Beijing: ["Tiananmen", "Great Wall"],
  Shanghai: ["Oriental Pearl", "The Bund"]
};


const DynamicFieldSet = () => {
  const [form] = Form.useForm();
  const onFinish = (values) => {
    console.log('Received values of form:', values, form);
  };

  const handleChange = () => {
  };


  const handleFieldsChange = (changedFields, allFields) => {
    console.log('handleFieldsChange---1', changedFields)

    const allFormData = form.getFieldsValue()
    if (cloneDeep(changedFields)[0].name.pop() === 'city') {
      sights[changedFields[0].value].forEach((item, index) => {
        allFormData.params[changedFields[0].name[1]].cityInfo = {
          ...allFormData.params[changedFields[0].name[1]].cityInfo,
          [`a${index}`]: {
            sight: item,
            keyValue: undefined
          }
        }
      })
    }
    console.log('handleFieldsChange---2', changedFields, allFormData)

    if (cloneDeep(changedFields)[0].name.pop() === 'price') {
      const curChangeFields = cloneDeep(changedFields[0].name)
      curChangeFields.pop()
      let needChangeField = allFormData
      curChangeFields.forEach(item => {
        needChangeField = needChangeField[item]
      })
      if (needChangeField && needChangeField.keyValue) {
        needChangeField.keyValue = undefined 
      }
    }

    console.log('handleFieldsChange---4', changedFields, allFormData)

    form.setFieldsValue(allFormData)
  }

  const handleValuesChange = (changedFields, allFields) => {
    console.log('handleFieldsChange---1111', changedFields)
  }
  return (
    <Form name="dynamic_form_item" {...formItemLayoutWithOutLabel} onFinish={onFinish} form={form} onFieldsChange={handleFieldsChange} onValuesChange={handleValuesChange}>
        <Form.Item
          name='templateName'
          style={{width: 100, marginRight: 30}}
          initialValue={'template'}
        >
          <Input  />
        </Form.Item>
        <Form.List
          name="params"
          rules={[
            {
              validator: async (_, names) => {
                if (!names || names.length < 1) {
                  return Promise.reject(new Error('At least 2 passengers'));
                }
              },
            },
          ]}
        >
          {(fields, { add, remove }, { errors }) => (
            <>
              {fields.map((field, index) => {
         console.log(field)
                return <Form.Item
                  {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                  label={index === 0 ? 'Passengers' : ''}
                  required={false}
                  key={field.key}
                >
                  <Form.Item
                    {...field}
                    validateTrigger={['onChange', 'onBlur']}
           name={[field.name, 'city']}
           key={`${field.key}_key`}
                    noStyle
                  >
            <Select options={areas} onChange={handleChange} />
          </Form.Item>
          
          {/* <Form.Item
                    // {...field}
                    validateTrigger={['onChange', 'onBlur']}
           name={[field.name, 'cityInfo', field.name]}
           key={`${field.key}_value`}
                    noStyle
                  > */}
                    {
                      <Form.Item shouldUpdate={(prevValues, curValues) => {
                        console.log('shouldUpdate', prevValues, curValues)
                        return prevValues?.params[`${field.name}`]?.city === curValues?.params[`${field.name}`]?.city || prevValues?.params[`${field.name}`]?.cityInfo === curValues?.params[`${field.name}`]?.cityInfo || prevValues?.params[`${field.name}`]?.cityInfo[`a${field.name}`].price === curValues?.params[`${field.name}`]?.cityInfo[`a${field.name}`].price
                      }}>
                      {() => {
                        return (
                          form.getFieldValue(['params', field.name,'city']) && sights[form.getFieldValue(['params', field.name,'city'])].map((item, idx) => {
                            return <div key={item} style={{display: "flex"}}>
                              <Form.Item
                                name={[field.name, 'cityInfo', `a${idx}`, 'sight']}
                                style={{width: 100, marginRight: 30}}
                                fieldKey={[field.fieldKey, "value", 'cityInfo', `a${idx}`, 'sight']}
                              >
                                <Input />
                              </Form.Item>
                              <Form.Item
                                name={[field.name,'cityInfo',`a${idx}`, 'price']}
                                style={{width: 100, marginRight: 30}}
                                fieldKey={[field.fieldKey, "value",'cityInfo',`a${idx}`, 'price']}
                              >
                                <Select options={type} />
                              </Form.Item>
                              <Form.Item
                                label="keyValue"
                                name={[field.name,'cityInfo',`a${idx}`,"keyValue"]}
                                fieldKey={[field.fieldKey, "value",'cityInfo',`a${idx}`,"keyValue"]}
                              >
                                {form.getFieldValue(['params', field.name,'cityInfo',`a${idx}`, 'price']) ===
                                "free" ? (
                                  <DatePicker />
                                ) : (
                                  <Input />
                                )}
                              </Form.Item>
                            </div>
                          })
                        );
                      }}
                    </Form.Item>
                    }
                  {/* </Form.Item> */}
                  {fields.length > 1 ? (
                    <MinusCircleOutlined
                      className="dynamic-delete-button"
                      onClick={() => remove(field.name)}
                    />
                  ) : null}
                </Form.Item>
        })}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  style={{ width: '60%' }}
                  icon={<PlusOutlined />}
                >
                  Add field
                </Button>
              
                <Form.ErrorList errors={errors} />
              </Form.Item>
            </>
          )}
        </Form.List>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
   );
  };
  
  export default DynamicFieldSet;